package com.shengdong.water.code.viewmodel

import com.shengdong.water.base.BaseViewModel
import com.shengdong.water.code.bean.Outlet
import com.shengdong.water.code.bean.TreeNode
import com.shengdong.water.code.repository.ApiRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject

@HiltViewModel
class VideoMonitorViewModel @Inject constructor(
    private val repository: ApiRepository
) : BaseViewModel()  {
    private val _outlets = MutableStateFlow<MutableList<Outlet>>(mutableListOf())
    val outlets:StateFlow<MutableList<Outlet>> = _outlets

    private val _regionStructure = MutableStateFlow<MutableList<TreeNode>>(mutableListOf())
    val regionStructure:StateFlow<MutableList<TreeNode>> = _regionStructure

    private val _cameraUrl = MutableStateFlow<Any>("")
    val cameraUrl:StateFlow<Any> = _cameraUrl

    fun getAllOutlets() {
        handleRequest(
            showLoading = true,
            flow = repository.getAllOutlets(),
            onSuccess = { _outlets.value = it },
            onError = { code ,msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError(msg)
                }
            },
            onToast =  {
                it
            },
            onException = {e ->
                showError("发生错误: ${e.message}")
            },
        )
    }

    fun getRegionStructure() {
        handleRequest(
            showLoading = true,
            flow = repository.getRegionStructure(),
            onSuccess = { _regionStructure.value = it },
            onError = { code ,msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError(msg)
                }
            },
            onToast =  {
                it
            },
            onException = {e ->
                showError("发生错误: ${e.message}")
            },
        )
    }

    fun getVideoCameraUrl(cameraIndexCode: String) {
        handleRequest(
            showLoading = true,
            flow = repository.getCameraUrl(cameraIndexCode, protocol= "hls"),
            onSuccess = { _cameraUrl.value = it },
            onError = { code ,msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError(msg)
                }
            },
            onToast =  {
                it
            },
            onException = {e ->
                showError("发生错误: ${e.message}")
            },
        )
    }
}